package com.ganinfo.common.aliyun;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.CopyObjectResult;
import com.aliyun.oss.model.ListObjectsRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;

public class AliOSSTool {

	private OSSClient client=null;
	
	public static AliOSSTool aliOssTool;
	public static boolean isInit=false;
	private static String access_id="";
	private static String access_key="";
	private static String default_bucket="";
	private static String end_point="";
	private static String end_point_inner="";
	private static boolean isInESC=false;
	private static long daymilsecond=24*60*60*1000;
	
	private AliOSSTool() {
		String ep=end_point;
		if(isInESC){
			ep=end_point_inner;
		}
		
		client=new OSSClient(ep,access_id, access_key);
	}
	
	@SuppressWarnings("rawtypes")
	static public boolean init(String key,String secret,String endpoint,String defaultBucket,String innerpoint,boolean isecs){
		access_id=key;
		access_key=secret;
		default_bucket=defaultBucket;
		end_point=endpoint;
		end_point_inner=innerpoint;
		isInESC=isecs;
		try {
			getInstance();
			List lst=aliOssTool.getBuckets();
			if(lst!=null){
				isInit=true;
			}
		} catch (Exception e) {
			System.out.println("阿里云存储OSS初始化错误:"+e.getMessage());
			e.printStackTrace();
		}
		
		
		return isInit;
	}
	
	static public AliOSSTool getInstance(){
		if(aliOssTool==null)
			aliOssTool=new AliOSSTool();
		return aliOssTool;
	}
	
	//----------具体操作-----------
	
	
	/**
	 * @author kevin
	 * 根据原图的key,返回list,包含缩略图的key
	 */
	public List<String> getKeyNameList(String bucketName,String key){
		List<String> returnlist = new ArrayList<String>();
		
		ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
		// 递归列出原图目录下的所有文件
		listObjectsRequest.setPrefix("files/img/"+key);
		ObjectListing listing = client.listObjects(listObjectsRequest);

		// 遍历该文件所有
		for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
		    System.out.println(objectSummary.getKey());
		    returnlist.add(objectSummary.getKey());
		}
		//System.out.println(returnlist.size());
		return returnlist;
	}
	
	public List<String> getKeyNameList(String key){
		return getKeyNameList(default_bucket,key);
	}
	
	/**
	 * 获取所有的bucket
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public List getBuckets(){
	    List<String> lst=null;
	    try {
	    	List<Bucket> buckets=client.listBuckets();
	    	if(buckets!=null){
	    		lst=new ArrayList<String>();
	    		for (Bucket bucket : buckets) {
					lst.add(bucket.getName());
				}
	    	}
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("获取bucket列表错误:"+e.getMessage());
			e.printStackTrace();
		}
	    return lst;
	}
	/**
	 * 上传文件
	 * @param bucket
	 * @param key 文件路径，如果包含/自动生成分割的目录
	 * @param data
	 * @param mimetype 类型
	 * @param suffix 可存储文件的后缀名称
	 * @return
	 */
	public boolean putObject(String bucket,String key,byte[] data,String mimetype,String suffix){
		boolean flag=false;
		if(data==null ) return flag;
		try {
			ObjectMetadata metadata=new ObjectMetadata();
			metadata.setContentLength(data.length);
			metadata.setContentType(mimetype);
			if(suffix.length()>0){
				metadata.addUserMetadata("suffix", suffix);
			}
			InputStream input=new ByteArrayInputStream(data);
			
					
			PutObjectResult result=client.putObject(bucket, key, input, metadata);
			if(result!=null&& result.getETag().length()>0){
				flag=true;
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("OSS 上传错误："+e.getMessage());
			e.printStackTrace();
		}
		return flag;
	}
	public boolean putObject(String key,byte[] data,String mimetype,String suffix){
		return putObject(default_bucket,key, data, mimetype,suffix);
	}
	public boolean putObject(String key,byte[] data,String suffix){
		return putObject(default_bucket,key, data, "application/zip",suffix);
	}
	public boolean putObject(String key,byte[] data){
		return putObject(default_bucket,key, data, "application/zip","");
	}
	
	public boolean copyObject(String bucket,String key,String objBucket,String objKey){
		boolean flag=false;
		if(key==null || key.length()<1 ) return flag;
		try {
			
			CopyObjectResult result=client.copyObject(bucket, key, objBucket, objKey);
			if(result!=null&& result.getETag().length()>0){
				flag=true;
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("OSS copy file错误："+e.getMessage());
			e.printStackTrace();
		}
		return flag;
	}
	public boolean copyObject(String key,String objkey){
		return copyObject(default_bucket, key, default_bucket, objkey);
	}
	
	/**创建文件夹*/
	public boolean createFolder(String bucket,String folder){
		boolean flag=false;
		if(folder==null || folder.length()<1 ) return flag;
		try {
			ObjectMetadata metadata=new ObjectMetadata();
			metadata.setContentLength(0);
			byte[] buffer = new byte[0];
			ByteArrayInputStream in = new ByteArrayInputStream(buffer);  
			metadata.setContentLength(0);
			if(!folder.endsWith("/")){
				folder+="/";
			}
			PutObjectResult result=client.putObject(bucket,folder, in, metadata);
			if(result!=null&& result.getETag().length()>0){
				flag=true;
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("OSS 创建文件夹错误："+e.getMessage());
			e.printStackTrace();
		}
		return flag;
	}
	
	public boolean createFolder(String folder){
		return createFolder(default_bucket, folder);
	
	}
	/**
	 * 获取数据内容
	 * @param bucket
	 * @param key
	 * @return
	 */
	public byte[] getObject(String bucket,String key){
		byte[] data=null;
		try {
			OSSObject obj= client.getObject(bucket, key);
			
			 InputStream input=obj.getObjectContent();
			 int count=(int)obj.getObjectMetadata().getContentLength();
			 data=new byte[count];
			 input.read(data);
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("OSS 下载错误："+e.getMessage());
			e.printStackTrace();
		}
		return data;
	}
	public byte[] getObject(String key){
		return getObject(default_bucket, key);
	}
	
	
	public String getDownLoadUrl(String bucket,String key){
		String url="";
		try {
			Date dt=new Date();
			dt=new Date( dt.getTime()+daymilsecond);
			URL urlObj= client.generatePresignedUrl(bucket, key,dt);
			if(urlObj!=null){
				url=urlObj.toExternalForm();
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			System.out.print("OSS 获取下载地址错误："+e.getMessage());
			e.printStackTrace();
		}
		return url;
	}
	public String getDownLoadUrl(String key){
		return getDownLoadUrl(default_bucket, key);
	}
	
	public String getPubDownLoadUrl(String bucket,String key){
		String url="";
		try {
			Date dt=new Date();
			dt=new Date( dt.getTime()+daymilsecond);
			url=end_point+"/"+default_bucket+"/"+key;
		} catch (Exception e) {
			// TODO: handle exception
			System.out.print("OSS 获取公共下载地址错误："+e.getMessage());
			e.printStackTrace();
		}
		return url;
	}
	public String getPubDownLoadUrl(String key){
		return getPubDownLoadUrl(default_bucket, key);
	}
	//===============操作================
	
	@SuppressWarnings("rawtypes")
	public static void main(String args[]){
//		SystemConfig.printlog("建立阿里OSS服务连接:");
		String key = "n9UouodoQhIOMiqh"; //SystemConfig.params.get("aliosskey");
		String secret = "jgEjxRJ8daye0E1OoOOE0YcE6aJbee";//SystemConfig.params.get("aliosssecret");
		String endpoint= "http://oss-cn-beijing.aliyuncs.com";//SystemConfig.params.get("aliossendpoint");
		String defaultbucket= "linjuyun";//SystemConfig.params.get("defaultbucket");
		String innerendpoint= "http://oss-cn-beijing-internal.aliyuncs.com";//SystemConfig.params.get("aliossendpointinternal");
		String isinserver="false";//SystemConfig.params.get("isinserver");
		boolean isinECS=false;
		if("true".equals(isinserver)){
			isinECS=true;
		}
		try {
			boolean flag=AliOSSTool.init(key, secret, endpoint, defaultbucket,innerendpoint,isinECS);
			System.out.println("连接阿里OSS服务："+(flag?"成功":"失败"));
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(String.format("连接阿里OSS服务出错：%1$s.", e.getMessage()));
		}
		
		
		
		List list = AliOSSTool.getInstance().getKeyNameList("13/76/1376D210D66C8AF6A7F889C56C3EE390");
		System.out.println(list.size());
		/*String aid="kgsoPuMtyPcWOjXA";
		String akey="BOLbqkB0pz8FZNuxvJkon0HUVMCZsn";
		String endpoint="http://oss-cn-beijing.aliyuncs.com";
		String innerpont="http://oss-cn-beijing-internal.aliyuncs.com";
		boolean isinserver=false;
		
		北京节点外网地址：oss-cn-beijing.aliyuncs.com
		北京节点内网地址：oss-cn-beijing-internal.aliyuncs.com
		String defaultBucket="gayogo";
		boolean flag=AliOSSTool.init(aid, akey, endpoint,defaultBucket,innerpont,isinserver);
		if(!flag){
			System.out.print("初始化失败");
			return;
		}*/
		
		
		//上传文件测试
		
		/*try {
			
			File file=new File("e:\\1.jpg");
			FileInputStream input=new FileInputStream(file);
			byte[] data=new byte[input.available()];
			input.read(data);
			String key="test1/b/bs";
			
			flag=AliOSSTool.getInstance().putObject( key,  data,"application/zip");
			if(!flag){
				System.out.println("上传文件失败");
				return;
			}
			System.out.println("上传文件成功");
			
			
			//获取文件的地址：
			String url=AliOSSTool.getInstance().getDownLoadUrl(key);
			System.out.println("下载地址："+url);
			//download file 
			
			byte[] filedata=AliOSSTool.getInstance().getObject( key);//( key,  data,"application/zip");
			File filedown=new File("e:\\1download.jpg");
			FileOutputStream output=new FileOutputStream(filedown);
			output.write(filedata);
			System.out.println("下载存储到："+filedown.getAbsolutePath());
			*/
			//创建文件
			/*String folder = "abc/cde";
			AliOSSTool.getInstance().createFolder(defaultBucket, folder);*/
		/*} catch (Exception e) {
			// TODO: handle exception
		}*/
		
		
	}

}
